from flask import jsonify, render_template
from flask.json import JSONEncoder as _JSONEncoder
from jieba.analyse import extract_tags  # 词云会用到
import utils
from utils import *
from flask_paginate import Pagination, get_page_parameter
from werkzeug.security import generate_password_hash, check_password_hash
from flask import Flask, redirect, render_template, request, session, url_for
import pymysql
app = Flask(__name__, static_url_path='/static')
app.config['SECRET_KEY'] = 'mysecretkey'

# 主页路由
@app.route('/')
def index():
    # 获取 bs 数据库中的实时股票信息
    stock_data=get_all_data()
    # 处理查询请求
    query = request.args.get('query')
    if query:
        stock_data = [
            stock for stock in stock_data if query in stock['code'] or query in stock['name']]
 

     # 排序功能
    sort = request.args.get('sort', default=None)
    order = request.args.get('order', default='asc')
    if sort is not None:
        stock_data = sorted(
            stock_data, key=lambda k: k[sort], reverse=True if order == 'desc' else False)

    # 分页功能
    page = request.args.get(get_page_parameter(), type=int, default=1)
    per_page = 10
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    pagination = Pagination(page=page, per_page=per_page, total=len(
        stock_data), css_framework='bootstrap4')

    return render_template('index.html', stock_data=stock_data[start_index:end_index], pagination=pagination, sort=sort, order=order)

# 股票历史信息路由
@app.route('/history', methods=['GET', 'POST'])
def history():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    if request.method == 'POST':
        # 根据用户输入获取历史股票信息
        conn2 = pymysql.connect(
            host='localhost', port=3306, user='root', password='123456', db='history')
        stock_name = request.form['stock_name']
        stock_history = get_historical_stock_info(conn2, stock_name)
        conn2.close()
        if len(stock_history) > 0:
            # 使用 plotly 绘制股票历史信息
            plot = plot_stock_history(stock_history)
            bb = plot_bollinger_bands(stock_history)
            macd_fig = plot_macd(stock_history)
            rsi_fig = plot_rsi(stock_history)
            vb = plot_volume_bar(stock_history)
            sa = plot_scatter(stock_history)
            return render_template('history.html', plot=plot, macd_fig=macd_fig, rsi_fig=rsi_fig, bb=bb, vb=vb, sa=sa)
        else:
            return render_template('history.html', error='没有找到 {} 的历史数据'.format(stock_name))
    else:
        return render_template('history.html')

# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']

        # 检查用户名和邮箱是否已经存在
        conn = pymysql.connect(host='localhost', port=3306,
                               user='root', password='123456', db='bs')
        cursor = conn.cursor()
        cursor.execute(
            'SELECT * FROM users WHERE username=%s OR email=%s', (username, email))
        result = cursor.fetchone()
        if result:
            error = '用户名或邮箱已经存在'
            conn.close()
            return render_template('register.html', error=error)

        # 将新用户信息插入到数据库中
        hashed_password = generate_password_hash(password)
        cursor.execute('INSERT INTO users (username, password, email) VALUES (%s, %s, %s)',
                       (username, hashed_password, email))
        conn.commit()
        conn.close()

        return redirect(url_for('login'))

    return render_template('register.html')


# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # 在数据库中查找用户信息
        conn = pymysql.connect(host='localhost', port=3306,
                               user='root', password='123456', db='bs')
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM users WHERE username=%s', (username,))
        user = cursor.fetchone()
        conn.close()

        # 检查用户是否存在，并验证密码是否正确
        if user and check_password_hash(user[2], password):
            session['user_id'] = user[0]
            session['username'] = user[1]
            return redirect(url_for('index'))
        else:
            error = '用户名或密码错误'
            return render_template('login.html', error=error)

    return render_template('login.html')


# 注销路由
@app.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('username', None)
    return redirect(url_for('index'))


# 可视化路由
@app.route("/main")
def main():
    if 'user_id' not in session:
        return redirect(url_for('login'))
    rows = utils.get_LSTM_data()

    # 渲染模板并传递查询结果
    return render_template("main.html",predictions=rows)





# 可视化相关



@app.route('/l1')
def get_l1_data():  # 单价
    data = utils.get_l1_data()
    price = []
    name = []
    for k, v in data:
        price.append(float(k))
        name.append(v)
    return jsonify({"price": price, "name": name})


@app.route('/l2')
def get_l2_data():  # 涨跌额
    data = utils.get_l2_data()
    m = []
    n = []
    da = list(data)
    for i in da:
        l = list(i)
        a = l[0]
        b = l[1]
        m.append(a)
        n.append(b)
    return jsonify({"name": m, "Iad": n})


@app.route('/l3')
def get_l3_data():  # 各行业市值的平均值
    data = utils.get_l3_data()
    industry = []
    avg_market_value = []
    for k, v in data:
        industry.append(k)
        avg_market_value.append(float(v))
    return jsonify({"industry": industry, "avg_market_value": avg_market_value})


@app.route('/r1')
def get_r1_data():  # 各个行业的涨跌情况
    data = utils.get_r1_data()
    n = []
    c1 = []
    c2 = []
    da = list(data)
    for i in da:
        l = list(i)
        s = l[0]
        t = l[1]
        y = l[2]
        d = int(t)-int(y)
        n.append(s)
        c1.append(t)
        c2.append(d)
    return jsonify({"n": n, "c1": c1, "c2": c2})

@app.route('/r2')
def get_r2_data():  # 每个行业的股票上涨的分别占所有上涨股票的比值
    data = utils.get_r2_data()
    industry = []
    increase_ratio = []
    for row in data:
        industry.append(row[0])
        increase_ratio.append(row[1])
    return jsonify({"industry": industry, "increase_ratio": increase_ratio})

@app.route('/r3')
def get_wordcloud_data():

    results = utils.get_r3_data()

    # 构建词云图数据
    wordcloud_data = []
    for result in results:
        wordcloud_data.append({'name': result[0], 'value': result[1]})
    # 返回词云图数据
    return jsonify({"wordcloud_data": wordcloud_data})


if __name__ == '__main__':
    app.run(debug=True)
